package com.oa.web;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.oa.entity.Dept;
import com.oa.service.DeptService;
@WebServlet(urlPatterns="/deptServlet")
public class DeptServlet  extends HttpServlet{

	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		String dname  =req.getParameter("dname");
		String loc  =req.getParameter("loc");
		Dept dept = new Dept();
		dept.setDname(dname);
		dept.setLoc(loc);
		//连接表示层和业务层
		ServletContext application = req.getServletContext();
		WebApplicationContext ctx = (WebApplicationContext)application.getAttribute(  WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE  );
		DeptService deptService = (DeptService) ctx.getBean("deptService");
		//第2种获取Spring容器的方法
		//WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(req.getServletContext());
		
		//方法调用
		int count = deptService.saveDept(dept);
		if(count > 0){
			req.setAttribute("msg", "添加成功......");
			req.getRequestDispatcher("success.jsp").forward(req, resp);
		}
		
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
}
